<template>
  <div class="alarmConfiguration zy-content">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">{{ $t("common.company") }}</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.companyId"
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}`"
                  @on-change="getBackupList($event)"
              >
                <Option
                    v-for="item of companyList"
                    :value="item.id"
                    :key="item.code"
                    :label="item.fullName"
                ></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">仓库位置</p>
            <div class="ipt">
              <Cascader
                  clearable
                  ref="cascader"
                  change-on-select
                  :data="orgList"
                  v-model="searchParams.functionLocation"
                  placeholder="请选择"
              ></Cascader>
            </div>
          </div>
        </Col>
        <!-- backupName   backupNo-->
        <Col span="4">
          <div>
            <p class="label">{{ $t("common.WarehouseNo") }}</p>
            <div class="ipt">
              <Input
                  type="text"
                  v-model="searchParams.backupNo"
                  clearable
                  :placeholder="`${$t('common.inputInfo')}`"
                  :maxlength="32"
              ></Input>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">状态</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.status"
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}`"
              >
                <Option value="1">启用</Option>
                <Option value="0">禁用</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button
                  class="search-btn"
                  type="primary"
                  v-if="checkBtnPermission.storeHouseList"
                  @click="changeNum()"
              >{{ $t("common.Query") }}
              </Button>
              <Button
                  class="reset-btn"
                  @click="reset()"
                  v-if="checkBtnPermission.storeHouseList"
              >{{ $t("common.reset") }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
      <!-- 批量删除 批量导出  批量导入 下载模板 新增-->
      <div class="btns clear">
        <span class="title">{{ $t("common.listInformation") }}</span>
        <Button
            @click="createfaultCodeShowH"
            v-if="checkBtnPermission.storeHouseAdd"
        >{{ $t("common.New") }}
        </Button>
        <Button
            @click="delFaultCodeShowClick"
            v-has="'storeHouseBatchDelete'"
        >{{ $t("common.batchDelete") }}
        </Button>
        <Button
            @click="exportTemplateClick"
            v-if="checkBtnPermission.storeHouseExport"
        >{{ $t("common.batchExport") }}
        </Button>
        <Button
            @click="importExcelShow"
            v-if="checkBtnPermission.storeHouseImport"
        >{{ $t("common.Import") }}
        </Button>
        <Button
            @click="exportTemplate"
            v-if="checkBtnPermission.storeHouseTemplate"
        >{{ $t("common.Download") }}
        </Button>
        <Button
            @click="getTableColumns(columns)"
        >{{ handleContextMenuStatus ? $t("显示操作栏") : $t("隐藏操作栏") }}
        </Button>
      </div>
      <!-- 表格 -->
      <div class="tableContent">
        <Table
            class="resizable-table"
            border
            @on-column-width-resize="onColumnWidthResize"
            :columns="columnsList"
            ellipsis
            ref="selection"
            stripe
            :data="dataArr"
            @on-selection-change="onSelectChange"
        >
          <template slot-scope="{ row }" slot="status">
            <span>
              {{ row.status == 1 ? '启用' : '禁用' }}
            </span>
          </template>
          <template slot-scope="{ row }" slot="action">
            <span
                class="operationBtn"
                @click="createfaultCodeShowH(row)"
                v-if="checkBtnPermission.storeHouseEdit"
            >
              <i class="iconfont zy-common-bianji"></i>
              {{ $t("common.Edit") }}
            </span>
            <span
                class="operationBtn"
                @click="updateStatus(row, row.status == 1 ? 0 : 1)"
                v-if="checkBtnPermission.storeHouseEdit"
            >
              <i class="iconfont zy-common-bianji" v-if="row.status === 0"></i>
              <i class="iconfont zy-common-bianji" v-else></i>
              {{ row.status == 1 ? '禁用' : '启用' }}
            </span>
            <span
                class="operationBtn"
                @click="delPrrShowH(row)"
                v-if="checkBtnPermission.storeHouseDelete"
            >
              <i class="iconfont zy-common-shanchu"></i>
              {{ $t("common.Delete") }}
            </span>
          </template>
        </Table>
      </div>
      <!-- 分页 -->
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="delIds.length"/>
        <Page
            :total="total"
            :page-size="pageSize"
            :page-size-opts="pageSizeOption"
            :current="pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
        />
      </div>
    </div>
    <!-- 新增编辑 -->
    <Modal :mask-closable="false" v-model="create" :title="addtitle" class="modal-content-layout">
      <Form
          ref="form"
          class="formList"
          :model="formItem"
          label-position="top"
          :rules="ruleValidate"
      >
        <FormItem :label="$t('common.company')" prop="companyId">
          <Select
              v-model="formItem.companyId"
              filterable
              clearable
              :placeholder="`${$t('common.selectInfo')}`"
              @on-change="getBackupList($event)"
          >
            <Option
                v-for="item of companyList"
                :value="item.id"
                :key="item.code"
                :label="item.name"
            ></Option>
          </Select>
        </FormItem>
        <FormItem label="仓库位置" prop="functionLocation">
          <Cascader
              clearable
              ref="cascader"
              :data="orgList"
              :disabled="addtitle == '编辑'"
              v-model="formItem.functionLocation"
              placeholder="请选择"
          ></Cascader>
        </FormItem>
        <FormItem label="仓库编号" prop="backupNo">
          <Input
              type="text"
              v-model="formItem.backupNo"
              :placeholder="`${$t('common.inputInfo')}`"
              :maxlength="32"
          ></Input>
        </FormItem>
        <FormItem label="仓库名称" prop="backupName">
          <Input
              type="text"
              v-model="formItem.backupName"
              :disabled="addtitle == '编辑'"
              :placeholder="`${$t('common.inputInfo')}`"
              :maxlength="32"
          ></Input>
        </FormItem>

        <FormItem label="现场仓" prop="onSiteWarehouse">
          <Select
              v-model="formItem.onSiteWarehouse"
              filterable
              clearable
              :placeholder="`${$t('common.selectInfo')}`"
          >
            <Option v-for="item of is" :value="item.name" :key="item.name" :label="item.name"></Option>
          </Select>
        </FormItem>

        <FormItem :label="$t('common.administrators')" prop="manageBy">
          <Select
              v-model="formItem.manageBy"
              filterable
              @on-change="manageChange"
              clearable
              :placeholder="`${$t('common.inputInfo')}`"
          >
            <Option
                v-for="(item, index) of createByOptions"
                :value="item.id"
                :key="index"
                :label="item.showName"
            ></Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('common.remarks')" prop="remark">
          <Input
              type="textarea"
              v-model="formItem.remark"
              :placeholder="`${$t('common.inputInfo')}`"
              :autosize="{ minRows: 2, maxRows: 5 }"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="create = false">
          {{ $t("common.Cancle") }}
        </Button>
        <Button type="primary" :loading="loading" @click="addOk('form')">
          {{ $t("maintenance.Confirmed") }}
        </Button>
      </div>
    </Modal>
    <!-- 请确认是否删除弹框 -->
    <Modal
        :mask-closable="false"
        v-model="delFaultCodeShowF"
        :title="$t('common.Delete')"
        class="modal-title-layout"
    >
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t("common.confirmDelete") }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="delFaultCodeShowF = false">
          {{
            $t("common.Cancle")
          }}
        </Button>
        <Button type="primary" :loading="loading" @click="deleteOk">
          {{
            $t("maintenance.Confirmed")
          }}
        </Button>
      </div>
    </Modal>
    <importExcelModal
        :importExcelStateF="importExcelState"
        v-if="importExcelState"
        @importExcelChange="importExcelChange"
    ></importExcelModal>
  </div>
</template>

<script>
import {
  searchApi,
  addApi,
  editApi,
  deleteApi,
  templateApi,
  exportApi,
  updateStatusApi
} from "@/api/spareParts/storeHouse.js";
import {
  getUserSelect,
  getCompany,
  getBackup,
  findOrgByToken
} from "@/api/index.js";
import importExcelModal from "@/components/importExcel.vue";
import fileDownload from "js-file-download";
import toggleTableOperation from "@/mixins/toggleTableOperation";
import recursion from "@/util/recursion";

export default {
  name: "storeHouse", //仓库配置
  components: {importExcelModal},
  mixins: [toggleTableOperation],
  data() {
    return {
      is: [
        {id: 1, name: "是"},
        {id: 2, name: "否"}
      ],
      companyList: [],
      backupList: [],
      shelfList: [],
      locationList: [],
      importExcelState: false /*批量导入*/,
      formItem: {},
      addtitle: "",
      allCheck: false,
      loading: false,
      create: false,
      searchParams: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      columns: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: `${this.$t("common.company")}`,
          key: "companyName",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          title: "仓库位置",
          key: "functionLocationName",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          title: `${this.$t("common.Warehouse")}`,
          key: "backupName",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          title: `${this.$t("common.WarehouseNo")}`,
          key: "backupNo",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          title: "是否为现场仓",
          key: "onSiteWarehouse",
          minWidth: 130,
          align: "center",
          resizable: true
        },
        {
          title: "状态",
          slot: "status",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          //title: '管理员',
          title: `${this.$t("common.owner")}`,
          key: "manageName",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          // title: '创建人',
          title: `${this.$t("common.CreateBy")}`,
          key: "createName",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          //title: '备注',
          title: `${this.$t("common.remarks")}`,
          key: "remark",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          //title: '创建时间',
          title: `${this.$t("common.CreateTime")}`,
          key: "createTime",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          //title: '操作',
          title: `${this.$t("common.operation")}`,
          slot: "action",
          fixed: "right",
          minWidth: 220,
          align: "center"
        }
      ],
      orgList: [], //功能位置
      dataArr: [],
      delFaultCodeShowF: false, //是否显示删除弹窗
      pageSizeOption: [10, 20, 30, 40],
      delIds: [],
      selection: [],
      checkBtnPermission: {},
      createByOptions: [],
      ruleValidate: {
        companyId: [
          {
            required: true,
            message: "请选择公司",
            trigger: "blur",
            type: "number"
          }
        ],
        backupNo: [
          {
            required: true,
            message: "请填写仓库编号",
            trigger: "change",
            type: "string"
          }
        ],
        backupName: [
          {required: true, message: "请填写仓库名称", trigger: "blur"}
        ],
        onSiteWarehouse: [
          {
            required: true,
            message: "请选择现场仓",
            trigger: "blur"
            // type: "number"
          }
        ],
        manageBy: [
          {
            required: true,
            message: "请选择管理员",
            trigger: "blur",
            type: "number"
          }
        ]
      }
    };
  },
  mounted() {
    this.getTableColumnsWidth(this.columns);
    this.getOrgList();
    this.searchList();
    this.getCompanyList();
    this.getUserList();
    let itemList = JSON.parse(window.localStorage.getItem("USER_URI"));
    for (let item of itemList) {
      if (item.code == "storeHouseList") {
        this.checkBtnPermission.storeHouseList = true;
      }
      if (item.code == "storeHouseAdd") {
        this.checkBtnPermission.storeHouseAdd = true;
      }
      if (item.code == "storeHouseDelete") {
        this.checkBtnPermission.storeHouseDelete = true;
      }
      if (item.code == "storeHouseEdit") {
        this.checkBtnPermission.storeHouseEdit = true;
      }
      if (item.code == "storeHouseExport") {
        this.checkBtnPermission.storeHouseExport = true;
      }
      if (item.code == "storeHouseImport") {
        this.checkBtnPermission.storeHouseImport = true;
      }
      if (item.code == "storeHouseTemplate") {
        this.checkBtnPermission.storeHouseTemplate = true;
      }
    }
  },
  watch: {
    "searchParams.companyId": {
      handler(val, oldVal) {
        this.backupId = null;
        this.$set(this.searchParams, "backupName", null);
        this.backupList = [];
      },
      deep: true
    }
  },
  methods: {
    manageChange(val) {
      console.log(val);
      const arg = this.createByOptions.find(item => item.id == val);
      if (arg) {
        this.formItem.manageName = arg.username;
      }
    },
    //获取公司
    getCompanyList() {
      getCompany()
          .then(res => {
            if (res.code === 200) {
              this.companyList = res.data;
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true
              });
            }
          })
          .finally(() => {
            this.loading = false;
          });
    },
    getOrgList() {
      let params = {
        level: 0
      };
      findOrgByToken(params).then(res => {
        if (res.code === 200) {
          const obj = {
            label: "name",
            value: "code",
            children: "children"
          };
          this.orgList = recursion.convertTree(res.data, obj);
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    //获取仓库
    getBackupList(data) {
      let params = {
        companyId: data
      };
      getBackup(params)
          .then(res => {
            if (res.code === 200) {
              this.backupList = res.data;
            }
          })
          .finally(() => {
            this.loading = false;
          });
    },
    //获取管理员
    getUserList() {
      getUserSelect()
          .then(res => {
            if (res.code === 200) {
              this.createByOptions = res.data.map(item => {
                return {
                  ...item,
                  showName: item.empno + "----" + item.username
                };
              });
            } else {
              this.createByOptions = [];
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true
              });
            }
          })
          .finally(() => {
            this.loading = false;
          });
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    //查询列表
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      for (let key in this.searchParams) {
        if (key == "functionLocation") {
          if (this.searchParams[key].length !== 0) {
            this.$set(params, key, [this.searchParams[key].at(-1)]);
          } else delete params[key];
        } else this.$set(params, key, this.searchParams[key]);
      }
      searchApi(params).then(res => {
        if (res.code === 200) {
          this.dataArr = res.data.records;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    // 更新状态
    updateStatus(row, status) {
      this.loading = true;
      updateStatusApi({
        id: row.id,
        status: status
      }).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$Message.success(status === 1 ? '启用成功' : '禁用成功');
          this.searchList();
        } else {
          this.$Message.error(status === 1 ? '启用失败' : '禁用失败');
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    //增加或编辑
    createfaultCodeShowH(row) {
      this.$refs.form.resetFields();
      if (row.id) {
        this.addtitle = `${this.$t("common.Edit")}`;
        this.formItem = {
          ...row
        };
      } else {
        this.addtitle = `${this.$t("common.New")}`;
        this.formItem = {
          companyId: null,
          backupNo: "",
          backupName: "",
          manageBy: null
        };
      }
      this.create = true;
    },
    addOk(name) {
      if (this.formItem.companyId) {
        const that = this;
        let res = this.companyList.find(
            item => item.id == that.formItem.companyId
        );
        if (res) {
          this.formItem.companyName = res.name;
        }
      }
      this.$refs[name].validate(valid => {
        if (!valid) {
          return;
        } else {
          this.loading = true;
          if (this.formItem.id) {
            editApi(this.formItem).then(res => {
              this.loading = false;
              if (res.code === 200) {
                this.changeNum();
                this.$Message.success("编辑成功");
                this.create = false;
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          } else {
            addApi(this.formItem).then(res => {
              this.loading = false;
              if (res.code === 200) {
                this.changeNum();
                this.$Message.success("新增成功");
                this.create = false;
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          }
        }
      });
    },
    //勾选列表
    onSelectChange(selection) {
      let myArray = [];
      selection.map((item, index) => {
        myArray.push(item.id);
      });
      this.delIds = myArray;
      if (selection.length > 0) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
    },
    //批量删除
    delFaultCodeShowClick() {
      if (this.delIds.length == 0) {
        this.$Message.warning({
          content: `${this.$t("common.deleteItems")}`,
          duration: 6,
          closable: true
        });
        return;
      } else {
        this.delFaultCodeShowF = true;
      }
    },
    //删除
    delPrrShowH(row) {
      //点击展示提示删除弹窗
      this.delFaultCodeShowF = true;
      this.delIds = [];
      this.delIds.push(row.id);
    },
    deleteOk() {
      this.loading = true;
      let params = this.delIds;
      deleteApi(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.changeNum();
          this.$Message.success("删除成功");
          this.allCheck = false;
          this.delFaultCodeShowF = false;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    //下载模板
    exportTemplate() {
      const filName = "仓库配置模板";
      templateApi().then(res => {
        fileDownload(res, filName + ".xlsx");
      });
    },
    //导入
    importExcelShow() {
      this.importExcelState = true;
    },
    importExcelChange(val) {
      this.importExcelState = false;
      if (val === "success") {
        this.changeNum();
      }
    },
    //导出
    exportTemplateClick() {
      let params = {
        delIds: this.delIds
      };
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key]);
        }
      }
      const filName = "仓库配置";
      exportApi(params).then(res => {
        fileDownload(res, filName + ".xlsx");
      });
    }
  }
};
</script>

<style scoped lang="scss">
.ivu-input-number {
  width: -webkit-fill-available;
}

.status-enable {
  color: #19be6b;
}

.status-disable {
  color: #ed4014;
}
</style>